package com.biqee.service.tb.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.biqee.dao.TbItemDAO;
import com.biqee.exception.Assert;
import com.biqee.model.common.PageInfoObject;
import com.biqee.model.db.TbItem;
import com.biqee.service.tb.TbItemService;

public class TbItemServiceImpl implements TbItemService {
	private  Logger log = Logger.getLogger(this.getClass());
	
	@Override
	public Integer save(TbItem tbItem) {
		Assert.assertNotNull(tbItem);
		Integer id = tbItem.getId();
		if(id != null) {
			update(tbItem);
			return id;
		} else {
			TbItem tbItemInDb = getByTbItemId(tbItem.getTbItemId());
			if(tbItemInDb == null) {
				return create(tbItem);
			} else {
				return tbItemInDb.getId();
			}
		}
	}
	
	@Override
	public Integer create(TbItem tbItem) {
		Assert.assertNotNull(tbItem);
		tbItem.setGmtCreate(new Date());
		tbItem.setGmtModified(new Date());		
		return tbItemDAO.create(tbItem);
	}
	
	@Override
	public int update(TbItem tbItem) {
		Assert.assertNotNull(tbItem);	
		return tbItemDAO.update(tbItem);
	}
	
	@Override
	public TbItem read(int id) {
		return tbItemDAO.read(id);
	}

	@Override
	public List<TbItem> listByPage(PageInfoObject page) {
		return this.tbItemDAO.listByPage(page);
	}

	@Override
	public int saveOrUpdateListByTbId(List<TbItem> list) {
		Assert.assertNotNull(list);
		int i = 0;
		for (TbItem tbItem : list) {
			try {
				this.save(tbItem);
				i++;
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		
		return i;
	}

	@Override
	public TbItem getByTbItemId(String tbItemId) {
		return this.tbItemDAO.readByTbItemId(tbItemId);
	}	
	

	private TbItemDAO tbItemDAO; 
	
	public void setTbItemDAO(TbItemDAO tbItemDAO) {
		this.tbItemDAO = tbItemDAO;
	}
}
